package com.example.shop_2302.search

import android.util.Log
import android.view.LayoutInflater
import android.widget.TextView
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SPUtils
import com.example.base.mvvm.BaseActivity
import com.example.shop_2302.R
import com.example.shop_2302.adapter.GoodsAdapter
import com.example.shop_2302.databinding.ActivitySearchBinding
import com.example.shop_2302.room.AppDbUtils
import com.example.shop_2302.room.Record
import com.google.android.material.chip.Chip
import java.text.SimpleDateFormat

@Route(path = "/app/SearchActivity")
class SearchActivity : BaseActivity<ActivitySearchBinding,SearchViewModel>() {
    lateinit var goodsAdapter: GoodsAdapter
    override fun initView() {
        goodsAdapter = GoodsAdapter()
        binding.rvGoods.adapter = goodsAdapter
        binding.rvGoods.layoutManager = GridLayoutManager(this,2)
        binding.search.setOnQueryTextListener(object:SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                //点击回车键后触发
                if(query!=null){
                    //Log.d("ssss", "onQueryTextSubmit: $query")
                    viewModel.search(query,10,1)
                    //调用数据进行保存
                    val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    val time = System.currentTimeMillis()
                    val timeStr = simpleDateFormat.format(time)
                    AppDbUtils.getDb().getRecordDao().insert(Record(query,timeStr,SPUtils.getInstance().getString("phone")))
                    queryRecord()//实现实时更新历史记录
                }
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                //文字发生变化后触发//实时查询更新
                if(newText!=null){
                    viewModel.search(newText,10,1)
                }
                return false
            }
        })
        //展示历史搜索记录
       queryRecord()

        //点击删除图标，将历史记录清空
        binding.delete.setOnClickListener {
            //先删除后台数据库
            AppDbUtils.getDb().getRecordDao().deleteAll(SPUtils.getInstance().getString("phone"))
            //再清除界面
            binding.cgRecord.removeAllViews()
        }

    }

    private fun queryRecord() {
        val query =
            AppDbUtils.getDb().getRecordDao().query(SPUtils.getInstance().getString("phone"))
        Log.d("sss", "initView: ${query.size}")
        query.reverse()//倒序，先展示最后一个搜索结果
        if(query.isNotEmpty()){
            binding.cgRecord.removeAllViews()//将下方子控件移除
            query.forEach {
                val chip = LayoutInflater.from(this).inflate(R.layout.item_record, null) as Chip
                chip.findViewById<TextView>(R.id.name).text = it.keyword
                binding.cgRecord.addView(chip)
                //点击chip,实现查询////注意不要点击X图标
                chip.setOnClickListener { it1->
                    binding.search.setQuery(it.keyword,true)
                }
                //点击X,能够删除对应的历史搜索记录
                chip.setOnCloseIconClickListener { it2->
                    //先删数据库
                    AppDbUtils.getDb().getRecordDao().delete(it)
                    //删除页面数据
                    binding.cgRecord.removeView(it2)
                }
            }
        }
    }

    override fun initData() {

        viewModel.searchSuccess.observe(this){
            if(it.code==200){
                goodsAdapter.data.clear()
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
            }

        }

    }

    override fun getViewModel(): Class<SearchViewModel>  = SearchViewModel::class.java

    override fun getLayout(): Int = R.layout.activity_search

}